//
//  ShellPledgeView.m
//  ShellWallert
//
//  Created by lvzhao on 2019/9/27.
//  Copyright © 2019年 VV. All rights reserved.
//

#import "ShellPledgeView.h"
#import "ShellPledgeViewModel.h"
#import "ShellChangeTeadePasswordViewController.h"
#import "YYKit.h"
#import "NSAttributedString+YYText.h"
#import "LZWebViewController.h"



@interface ShellPledgeView()

@property (nonatomic , strong) YYLabel *protocolLabel;
@property (nonatomic , assign) BOOL isSelect;

@property (nonatomic,strong) ShellPledgeViewModel *viewModel;

@property (nonatomic,strong) UIView *contentView;
@property (nonatomic,strong) NSMutableArray *numberBtns;

//选中的按钮
@property (nonatomic,strong) UIButton *selectBtn;

@property (nonatomic,strong) UIButton *pledgeBtn;
///输入框
@property (nonatomic,strong) UITextField *textField;
@end
@implementation ShellPledgeView
- (instancetype)initViewModel:(LZBaseViewModel *)viewModel
{
    self = [super init];
    if (self) {
        self.viewModel = (ShellPledgeViewModel *)viewModel;
        [self setupView];
    }
    return self;
}


#pragma mark - setupView
- (void)setupView{
    
    [self addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(25);
        make.left.mas_equalTo(15);
        make.width.mas_equalTo(K_SCREENWIDTH - 30);
        make.height.mas_equalTo(270);
    }];
    
    
    
    @weakify(self);
    [self.viewModel.reloadSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        switch ([x integerValue]) {
            case 1:
            {
                [self refreshUI];
            }
                break;
                
            default:
                break;
        }
    }];
    
    
    ///!!!:请阅读
    self.protocolLabel = [[YYLabel alloc]initWithFrame:CGRectMake(15, 100,K_SCREENWIDTH - 30, 45)];
    [self addSubview:self.protocolLabel];
    [self protocolIsSelect:NO];
    [self.protocolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
          make.top.mas_equalTo(self.contentView.mas_bottom).mas_offset(10);
          make.left.mas_equalTo(15);
          make.width.mas_equalTo(K_SCREENWIDTH - 30);
          make.height.mas_equalTo(60);
    }];
    
    ///!!!:质押
    [self.pledgeBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateNormal];
    [self.pledgeBtn setTitleColor:RGBA(255, 255, 255, 0.5) forState:UIControlStateDisabled];
    self.pledgeBtn.enabled = NO;
    self.pledgeBtn.adjustsImageWhenHighlighted = NO;
    [self addSubview:self.pledgeBtn];
    [self.pledgeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.protocolLabel.mas_bottom).mas_offset(25);
        make.left.mas_equalTo(15);
        make.width.mas_equalTo(K_SCREENWIDTH - 30);
        make.height.mas_equalTo(50);
    }];
    
    
    
    
    
    [[self.pledgeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {

        //质押的数量
        NSString *pledgeNumber = @"";
        if(self.selectBtn){
            //获取数组的元素
            NSArray *items = [self.viewModel.pledgeModel.pledgeAmount componentsSeparatedByString:@","];
            pledgeNumber = items[self.selectBtn.tag - 100];
        } else {
            pledgeNumber = self.textField.text;
        }
        
        if (pledgeNumber.length == 0)return;
        
        
        ShellUserDetailModel *detailModel = [LZToolCache getUserInfo];
        if(!detailModel.payPasswordFlag){
            //没有设置交易密码
            [LZToolView showAlertType:LZAlertViewTypeTipAlter withTitle:LZLocalizedString(@"提示") message:LZLocalizedString(@"请先设置交易密码") cancel:@"" sure:LZLocalizedString(@"确定") objectDict:@{@"textAlignment":@(NSTextAlignmentCenter)} cancelBlock:^(id  _Nullable object) {} sureBlock:^(id  _Nullable object) {
                ShellChangeTeadePasswordViewController *changeTeadePasswordVC = [[ShellChangeTeadePasswordViewController alloc] init];
                [LZTool.currentViewController.navigationController pushViewController:changeTeadePasswordVC animated:YES];
                  
            }];
            return;
        }
        
        
        [LZToolView showAlertType:LZAlertViewTypeTradePassword withTitle:LZLocalizedString(@"交易密码") message:LZLocalizedString(@"请输入交易密码") cancel:LZLocalizedString(@"取消") sure:LZLocalizedString(@"确定") objectDict:@{} cancelBlock:^(id  _Nullable object) { } sureBlock:^(id  _Nullable object) {
            @strongify(self);
                //发送请求 清算
            [self.viewModel pledgeNumber:pledgeNumber password:object];
        }];
    }];

}

- (void)protocolIsSelect:(BOOL)isSelect{
    
    //设置整段字符串的颜色
    NSDictionary *attributes = @{NSFontAttributeName:k_textFont(14), NSForegroundColorAttributeName:UIColorHex(0x678DA8)};
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:LZLocalizedString(@"我已认真阅读并同意 质押投资协议") attributes:attributes];

    //设置高亮色和点击事件
    [attributedString setTextHighlightRange:[[attributedString string] rangeOfString:LZLocalizedString(@"质押投资协议")] color:UIColorHex(0x4AB2E7) backgroundColor:UIColor.grayColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        NSLog(@"《质押投资协议》");
        LZWebViewController *webVc = [[LZWebViewController alloc] init];
        webVc.webUrl = @"https://www.tritonlab.net/pledgeAgreement.html";
        [LZTool.currentViewController.navigationController pushViewController:webVc animated:YES];
    }];
    self.protocolLabel.numberOfLines = 0;
    self.protocolLabel.attributedText = attributedString;
    self.protocolLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    self.protocolLabel.textAlignment = NSTextAlignmentCenter;
    
    
    
    //添加图片
    UIImage *image = [UIImage imageNamed:isSelect == NO ? @"icon_clause_unselect" : @"icon_clause_select"];
    YYAnimatedImageView *imageView= [[YYAnimatedImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, 0, 16, 16);
    NSMutableAttributedString *attachText= [NSMutableAttributedString attachmentStringWithContent:imageView contentMode:UIViewContentModeLeft attachmentSize:CGSizeMake(25, 25) alignToFont:[UIFont systemFontOfSize:14] alignment:YYTextVerticalAlignmentCenter];
        
    //将图片放在最前面
    [attributedString insertAttributedString:attachText atIndex:0];
     //插入到开头
//    [attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@" "] atIndex:1];
    @weakify(self);
    [attributedString setTextHighlightRange:[[attributedString string]  rangeOfString:attachText.string] color:[UIColor clearColor] backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        @strongify(self);
        self.isSelect = !self.isSelect;
        [self protocolIsSelect:self.isSelect];
        self.pledgeBtn.enabled = self.isSelect;
        NSLog(@"《质押投资协议》%d",self.isSelect);

    }];

    self.protocolLabel.attributedText = attributedString;

}

//回调
- (void)refreshUI{
    
    UILabel *tipLabel = [UILabel lz_labelWithText:self.viewModel.pledgeModel.descText fontSize:k_textFont(13) color:UIColorHex(0x678DA8)];
    CGFloat tipHeight = [tipLabel.text lz_textHeightWithFontSize:tipLabel.font withMaxWidth:K_SCREENWIDTH - 70];
    [self.contentView addSubview:tipLabel];
    
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(tipHeight);
    }];

    
    NSArray *items = [self.viewModel.pledgeModel.pledgeAmount componentsSeparatedByString:@","];
    
    
    
    UIButton *lastView = nil;
    //每个Item宽高
    CGFloat H = 40;
    CGFloat btnW = (K_SCREENWIDTH - 30 - 40 - 10)/3.0;
    //每行列数
    NSInteger rank = 3;
    //每列间距
    CGFloat rankMargin = 5;
    //每行间距
    CGFloat rowMargin = 20;
    for(int i = 0; i < items.count; i++){
        
        UIButton *numberBtn = [UIButton lz_buttonTitle:[NSString stringWithFormat:@"%@ USDT",items[i]] titleColor:UIColorHex(0x678DA8) fontSize:12];
        numberBtn.backgroundColor = UIColorHex(0x0D3354);
        numberBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
        numberBtn.tag = 100 + i;
        [numberBtn setTitleColor:UIColorHex(0xFFFFFF) forState:UIControlStateSelected];
        numberBtn.cornerRadius = 4;
        [self.contentView addSubview:numberBtn];
        
        //Item X轴
        CGFloat X = (i % rank) * (btnW + rankMargin) + 20;
        //Item Y轴
        NSUInteger Y = (i / rank) * (H +rowMargin);
        //Item top
        CGFloat top = tipHeight + 50;
        
        numberBtn.frame = CGRectMake(X, Y + top, btnW, H);
        
        lastView = numberBtn;
        
        [numberBtn addTarget:self action:@selector(numberBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.numberBtns addObject:numberBtn];
    }

    ///!!!:其他
    UIButton *otherBtn = [UIButton lz_buttonTitle:LZLocalizedString(@"其他") titleColor:UIColorHex(0x678DA8) fontSize:12];
    otherBtn.backgroundColor = UIColorHex(0x0D3354);
    otherBtn.tag = 2018;
    otherBtn.cornerRadius = 4;
    [self.contentView addSubview:otherBtn];
    [otherBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(lastView.mas_bottom).mas_offset(20);
        make.left.mas_equalTo(20);
        make.width.mas_equalTo(btnW);
        make.height.mas_equalTo(40);
    }];
    @weakify(self);
  
    
    UITextField *textField = [[UITextField alloc] init];
    textField.bColor = UIColorHex(0x11385E);
    textField.bWidth = 1;
    textField.keyboardType = UIKeyboardTypeNumberPad;
    textField.textColor = UIColorHex(0xFFFFFF);
    textField.font = k_textFont(15);
    textField.placeholder = LZLocalizedString(@"请输入数量");
    UIView *leftView = [UIView new];
    leftView.frame = CGRectMake(0, 0, 15, 40);
    textField.leftView = leftView;
    //设置显示模式为永远显示(默认不显示)
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.cornerRadius = 6;
    textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:textField.placeholder attributes:@{NSForegroundColorAttributeName: UIColorHex(0x678DA8)}];

    UILabel *usdtLabel = [UILabel lz_labelWithText:@"USDT   " fontSize:k_textFont(13) color:UIColorHex(0x8D99B2)];
    usdtLabel.frame = CGRectMake(0, 0, 70, 40);
    textField.rightView = usdtLabel;
    //设置显示模式为永远显示(默认不显示)
    textField.rightViewMode = UITextFieldViewModeAlways;
    self.textField = textField;
    [self.contentView addSubview:textField];
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(otherBtn.mas_centerY);
        make.left.mas_equalTo(otherBtn.mas_right).mas_offset(5);
        make.width.mas_equalTo(btnW * 2 + 5);
        make.height.mas_equalTo(40);
    }];
    
    
    [[textField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        @strongify(self);
        if(textField.text.length > 0){
            self.selectBtn = nil;
            for (UIButton *numBtn in self.numberBtns){
                [numBtn setTitleColor:UIColorHex(0x678DA8) forState:UIControlStateNormal];
                numBtn.backgroundColor = UIColorHex(0x0D3354);
            }
            [otherBtn setTitleColor:UIColorHex(0xFFFFFF) forState:UIControlStateNormal];
             otherBtn.backgroundColor = UIColorHex(0x4AB2E7);
        }
    }];
    
    [[otherBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
          @strongify(self);
          [x setTitleColor:UIColorHex(0xFFFFFF) forState:UIControlStateNormal];
          x.backgroundColor = UIColorHex(0x4AB2E7);
          self.selectBtn = nil;
          for (UIButton *numBtn in self.numberBtns){
              [numBtn setTitleColor:UIColorHex(0x678DA8) forState:UIControlStateNormal];
              numBtn.backgroundColor = UIColorHex(0x0D3354);
          }
         NSString *allowed = [NSString stringWithFormat:@"%f",self.viewModel.pledgeModel.allowed].saveDecimal;
         textField.text = allowed;
      }];
    
    
    ///!!!:当前信用分
    UILabel *currencyScoreLab = [UILabel lz_labelWithText:@"" fontSize:k_textFont(13) color:UIColorHex(0x678DA8)];
    [self.contentView addSubview:currencyScoreLab];
    [currencyScoreLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(otherBtn.mas_bottom).mas_offset(27);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(18);
    }];
    
    NSString *creditScore = [NSString stringWithFormat:@"%f",self.viewModel.pledgeModel.creditScore].saveDecimal;
    NSString *pledged = [NSString stringWithFormat:@"%f",self.viewModel.pledgeModel.pledged].saveDecimal;
    NSString *maxAllowed = [NSString stringWithFormat:@"%f",self.viewModel.pledgeModel.maxAllowed].saveDecimal;

    NSString *currencyScore = [NSString stringWithFormat:@"%@  %@",LZLocalizedString(@"当前信用分"),creditScore];
    NSMutableAttributedString *currencyScoreAttributedString = [NSAttributedString attributedString:currencyScore rangeTitle:LZLocalizedString(@"当前信用分") leftFont:k_textFont(13) rightFont:k_textFont(13) leftColor:UIColorHex(0xFFFFFF) rightColor:UIColorHex(0x678DA8)];
    currencyScoreLab.attributedText = currencyScoreAttributedString;
    

    ///!!!:当前已质押
    UILabel *currencyPledgeLab = [UILabel lz_labelWithText:@"" fontSize:k_textFont(13) color:UIColorHex(0x678DA8)];
    [self.contentView addSubview:currencyPledgeLab];
    [currencyPledgeLab mas_makeConstraints:^(MASConstraintMaker *make) {
          make.top.mas_equalTo(currencyScoreLab.mas_bottom).mas_offset(13);
          make.left.mas_equalTo(20);
          make.right.mas_equalTo(-20);
          make.height.mas_equalTo(18);
      }];
      NSString *currencyPledge = [NSString stringWithFormat:@"%@  %@ USDT",LZLocalizedString(@"当前已质押"),pledged];
      NSMutableAttributedString *currencyPledgeAttributedString = [NSAttributedString attributedString:currencyPledge rangeTitle:LZLocalizedString(@"当前已质押") leftFont:k_textFont(13) rightFont:k_textFont(13) leftColor:UIColorHex(0xFFFFFF) rightColor:UIColorHex(0x678DA8)];
      currencyPledgeLab.attributedText = currencyPledgeAttributedString;
    
    
    ///
    ///
    ///!!!:剩余可质押
    UILabel *surplusPledgeLab = [UILabel lz_labelWithText:@"" fontSize:k_textFont(13) color:UIColorHex(0x678DA8)];
    [self.contentView addSubview:surplusPledgeLab];
    
    [surplusPledgeLab mas_makeConstraints:^(MASConstraintMaker *make) {
          make.top.mas_equalTo(currencyPledgeLab.mas_bottom).mas_offset(13);
          make.left.mas_equalTo(20);
          make.right.mas_equalTo(-20);
          make.height.mas_equalTo(18);
      }];
      NSString *surplusPledge = [NSString stringWithFormat:@"%@  %@ USDT",LZLocalizedString(@"剩余可质押"),maxAllowed];
      NSMutableAttributedString *surplusPledgeAttributedString = [NSAttributedString attributedString:surplusPledge rangeTitle:LZLocalizedString(@"剩余可质押") leftFont:k_textFont(13) rightFont:k_textFont(13) leftColor:UIColorHex(0xFFFFFF) rightColor:UIColorHex(0x678DA8)];
      surplusPledgeLab.attributedText = surplusPledgeAttributedString;
    
  
    
    [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(25);
        make.left.mas_equalTo(15);
        make.width.mas_equalTo(K_SCREENWIDTH - 30);
        make.bottom.mas_equalTo(surplusPledgeLab.mas_bottom).mas_offset(30);
    }];
    
}





#pragma mark - action
- (void)numberBtnClick:(UIButton *)sender{
    UIButton *otherBtn =  [self.contentView viewWithTag:2018];
    [otherBtn setTitleColor:UIColorHex(0x678DA8) forState:UIControlStateNormal];
    otherBtn.backgroundColor = UIColorHex(0x0D3354);
    
//    numberBtClick
    for (UIButton *numBtn in self.numberBtns){
        [numBtn setTitleColor:UIColorHex(0x678DA8) forState:UIControlStateNormal];
        numBtn.backgroundColor = UIColorHex(0x0D3354);
    }
    [sender setTitleColor:UIColorHex(0xFFFFFF) forState:UIControlStateNormal];
    sender.backgroundColor = UIColorHex(0x4AB2E7);
    
    self.selectBtn = sender;
    self.textField.text = @"";
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self endEditing:YES];
    
}

#pragma mark - get && set
- (UIView *)contentView{
    if(!_contentView){
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = COLOR_TINT;
        _contentView.cornerRadius = 6;
    }
    return _contentView;
}

- (NSMutableArray *)numberBtns{
    if(!_numberBtns){
        _numberBtns = [NSMutableArray arrayWithCapacity:0];
    }
    return _numberBtns;
}

- (UIButton *)pledgeBtn{
    if(!_pledgeBtn){
        _pledgeBtn = [UIButton lz_buttonTitle:LZLocalizedString(@"质押") titleColor:RGBA(255, 255, 255, 1) fontSize:17];
        UIImage *highlightImage = [UIImage gradientImageWithColors:@[UIColorHex(0x65DFFE),UIColorHex(0x2C6FE)] rect:CGRectMake(0, 0, 200, 50)];
        [_pledgeBtn setBackgroundImage:highlightImage forState:UIControlStateNormal];
        _pledgeBtn.cornerRadius = 6;
        _pledgeBtn.layer.shadowOffset = CGSizeMake(0,2);
        _pledgeBtn.layer.shadowOpacity = 1;
        _pledgeBtn.layer.shadowRadius = 6;
    }
    return _pledgeBtn;
}
@end
